import {Action, getModule, Module, Mutation, VuexModule} from 'vuex-module-decorators'
import {RouteConfig} from 'vue-router'
import store from '@/store/store'

const hasPermission = (roles: string[], route: RouteConfig) => {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
};

export const filterAsyncRoutes = (routes: RouteConfig[], roles: string[]) => {
    const res: RouteConfig[] = [];
    routes.forEach(route => {
        const r = {...route};
        if (hasPermission(roles, r)) {
            if (r.children) {
                r.children = filterAsyncRoutes(r.children, roles)
            }
            res.push(r)
        }
    });
    return res
};

export interface IPermissionState {
    routes: RouteConfig[]
    dynamicRoutes: RouteConfig[]
}

@Module({dynamic: true, store, name: 'permission'})
class Permission extends VuexModule implements IPermissionState {
    public routes: RouteConfig[] = [];
    public dynamicRoutes: RouteConfig[] = [];

    @Action
    public setRouter(routers: RouteConfig[]) {
        // let accessedRoutes
        // if (roles.includes('admin')) {
        //   accessedRoutes = asyncRoutes
        // } else {
        //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        // }
        this.SET_ROUTES(routers)
    }

    @Mutation
    private SET_ROUTES(routes: RouteConfig[]) {
        this.routes = routes;
        this.dynamicRoutes = routes;
    }
}

export const PermissionModule = getModule(Permission);
